var util = require('../../../../../utils/util.js');
const getImgUrl = require('../../../../../config').getImgUrl
const addStudentEatRecordUrl = require('../../../../../config').addStudentEatRecordUrl
const getStudentEatListUrl = require('../../../../../config').getStudentEatListUrl
const addStudentSleepRecordUrl = require('../../../../../config').addStudentSleepRecordUrl
const getStudentSleepListUrl = require('../../../../../config').getStudentSleepListUrl

var app = getApp()
let msg;

Page({
  data: {
    current: 0,
    scroll_height: 900,
    studeentList: [
      {
        id: 0,
        name: '未发送'
      },
      {
        id: 1,
        name: '已发送'
      }
    ],
    array: ['未按时吃饭', '无特殊情况', '未认真吃饭', '未按时睡觉', '睡觉吵闹'],
    indicatorDots: false,
    autoplay: false,
    interval: 2000,
    duration: 100,
    defalut: '../../image/signIn/bg2.png',
    isscroll: true,
    ismodel: true,   // 是否要输入框
    pageData: [ // index 0 午餐数据 / index 1 午睡数据
      {
        isubmit: true, // 还有学生没有发送
        TabTitle: true,
        currentId: 0, // 未发送和已发送
        files: [],
        checkboxItem: {
          name: 'all',
          value: '全选',
          checked: true
        },
        situationIndex: 1,
        pics: [],     //本地上传图片的数组
        urlPics: [],  //转换为url的数组
        unsendStudentList: [], //午睡情况 未发送学生列表
        sendStudentList: [], //午睡情况 已发送学生列表
        studentId: '',       //发送和未发送那里的学生ID
        SendchildrenId: [],  //选择发送的学生ID
        inpText: '还有需要特别说明的吗？', //要什么要说的咩
        inpTextarea: '还有需要特别说明的吗？'
      },
      {
        isubmit: true,
        TabTitle: true,
        currentId: 0,
        files: [],
        checkboxItem: {
          name: 'all',
          value: '全选',
          checked: true
        },
        situationIndex: 1,
        pics: [],
        urlPics: [],
        unsendStudentList: [],
        sendStudentList: [],
        studentId: '',
        SendchildrenId: [],
        inpText: '还有需要特别说明的吗？',
        inpTextarea: '还有需要特别说明的吗？'
      }
    ]
  },

  onLoad: function() {
    var that = this;
    var time = util.formatTime(new Date());
    let sendEdId = [];
    this.setData({
      time: time
    });
    //还没有发送的学生
    wx.getStorage({
      key: 'teacherInfo',
      success: function(res) {
        let organizationId = res.data.organizationId
        let staffId = res.data.staffId

        that.setData({
          organizationId,
          staffId
        })

        that.getNotStudent()
        that.getNotSleepStudent()
        that.getSendedStudent()
        that.getSendedSleepStudent()
      },
    })
  },

  // 获取已经发送的学生(午餐)
  getSendedStudent:function(){
    let that = this
    wx.request({
      url: getStudentEatListUrl,
      data: {
        "organizationId": this.data.organizationId,
        "sendMessageType": "SENT",
        "staffId": this.data.staffId
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        let sendStudentList = res.data.data
        that.setData({
          'pageData[0].sendStudentList': sendStudentList,
        })
      }
    })
  },

  // 获取已经发送的学生(午睡)
  getSendedSleepStudent: function () {
    let that = this
    wx.request({
      url: getStudentSleepListUrl,
      data: {
        "organizationId": this.data.organizationId,
        "sendMessageType": "SENT",
        "staffId": this.data.staffId
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        let sendStudentList = res.data.data
        that.setData({
          'pageData[1].sendStudentList': sendStudentList,
        })
      }
    })
  },

  // 获取还没有发送的学生(午餐)
  getNotStudent: function (){
    let that = this
    wx.request({
      url: getStudentEatListUrl,
      data: {
        "organizationId": this.data.organizationId,
        "sendMessageType": "UNSENT",
        "staffId": this.data.staffId
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        let unsendStudentList = res.data.data
        if (unsendStudentList.length == 0) {
          that.setData({
            'pageData[0].isubmit': false
          })
        }

        let SendchildrenId = []

        for (let i = 0; i < unsendStudentList.length; i++) {
          unsendStudentList[i].isChange = true
          SendchildrenId.push(unsendStudentList[i].id)
        }

        that.setData({
          'pageData[0].unsendStudentList': unsendStudentList,
          'pageData[0].SendchildrenId':SendchildrenId
        })
      }
    })
  },

  // 获取还没有发送的学生(午睡)
  getNotSleepStudent: function () {
    let that = this
    wx.request({
      url: getStudentSleepListUrl,
      data: {
        "organizationId": this.data.organizationId,
        "sendMessageType": "UNSENT",
        "staffId": this.data.staffId
      },
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        let unsendStudentList = res.data.data
        if (unsendStudentList.length == 0) {
          that.setData({
            'pageData[1].isubmit': false
          })
        }

        let SendchildrenId = []

        for (let i = 0; i < unsendStudentList.length; i++) {
          unsendStudentList[i].isChange = true
          SendchildrenId.push(unsendStudentList[i].id)
        }

        that.setData({
          'pageData[1].unsendStudentList': unsendStudentList,
          'pageData[1].SendchildrenId': SendchildrenId
        })
      }
    })
  },

  //上传图片
  chooseImage: function(e) {
    var that = this;
    var pics = this.data.pageData[this.data.current].pics
    wx.chooseImage({
      count:3,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var imgsrc = res.tempFilePaths;
        pics = pics.concat(imgsrc);
        if (that.data.current == 0) {
          that.setData({
            'pageData[0].files': that.data.pageData[0].files.concat(imgsrc),
            'pageData[0].pics': pics
          });
        }
        else {
          that.setData({
            'pageData[1].files': that.data.pageData[1].files.concat(imgsrc),
            'pageData[1].pics': pics
          });
        }
      }
    })
  },

  //预览即将上传的东西
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.pageData[this.data.current].files // 需要预览的图片http链接列表
    })
  },

  // 选择情况
  bindPickerChange: function(e) {
    if (this.data.current == 0) {
      this.setData({
        'pageData[0].situationIndex': e.detail.value
      })
    }
    else {
      this.setData({
        'pageData[1].situationIndex': e.detail.value
      })
    }
  },

  // 操作全选按钮
  checkboxChange: function(e) {
    var checked = e.currentTarget.dataset.change

    // 处理id
    let SendchildrenId = []

    let unsendStudentList = this.data.pageData[this.data.current].unsendStudentList
    for (let i = 0; i < unsendStudentList.length; i++) {
      unsendStudentList[i].isChange = !checked
      if (checked === false) {
        SendchildrenId.push(unsendStudentList[i].id)
      }
    }

    if (this.data.current == 0) {
      this.setData({
        'pageData[0].unsendStudentList': unsendStudentList,
        'pageData[0].checkboxItem.checked': !checked,
        'pageData[0].SendchildrenId': SendchildrenId
      })
    }
    else {
      this.setData({
        'pageData[1].unsendStudentList': unsendStudentList,
        'pageData[1].checkboxItem.checked': !checked,
        'pageData[1].SendchildrenId': SendchildrenId
      })
    }
      
  

    this.setData({
      
    })
  },

  // 发送未发送
  sendChange: function(e) {
    if (this.data.current == 0) {
      this.setData({
        'pageData[0].currentId': e.detail.current
      })
    }
    else {
      this.setData({
        'pageData[1].currentId': e.detail.current
      })
    }
  },

  // 点击孩子照片未发送
  changeUnsend: function(e) {
    let that = this
    let key = e.currentTarget.dataset.key
    let id = e.currentTarget.dataset.id
    let unsendStudentList = that.data.pageData[this.data.current].unsendStudentList
    let SendchildrenId = that.data.pageData[this.data.current].SendchildrenId

    unsendStudentList[key].isChange = !unsendStudentList[key].isChange   // 选择不选择呢？

    let chooseAll = false
    if (unsendStudentList[key].isChange) {
      let result = unsendStudentList.filter(item => !item.isChange);
      chooseAll = result.length <= 0 ? true : false
    }

     //如果这个元素存在，就删除，如果不存在就添加
    let index = SendchildrenId.indexOf(id)
    switch (index){
      case -1:
        SendchildrenId.push(id)
        break;
      default:
        SendchildrenId.splice(index, 1)
    }

    if (this.data.current == 0) {
      this.setData({
        'pageData[0].checkboxItem.checked': chooseAll,
        'pageData[0].studentId': id,
        'pageData[0].unsendStudentList': unsendStudentList,
        'pageData[0].SendchildrenId': SendchildrenId
      })
    }
    else {
      this.setData({
        'pageData[1].checkboxItem.checked': chooseAll,
        'pageData[1].studentId': id,
        'pageData[1].unsendStudentList': unsendStudentList,
        'pageData[1].SendchildrenId': SendchildrenId
      })
    }
  },

  //有什么要说的咩
  inpText:function(e){
    if (this.data.current == 0) {
      this.setData({
        'pageData[0].inpText': e.detail.value
      })
    }
    else {
      this.setData({
        'pageData[1].inpText': e.detail.value
      })
    }
  },

  // submit
  submit: function() {
    wx.showLoading({
      title: '加载中',
    })
    let that = this

    let inpText = that.data.pageData[this.data.current].inpText;
    let SendchildrenId = that.data.pageData[this.data.current].SendchildrenId;
    let pics = that.data.pageData[this.data.current].pics
    let degree = 0;

    if (pics.length <= 0) {
      wx.hideLoading();
      wx.showModal({
        title: '警告',
        content: '请添加图片',
      })
      return;
    }
    // 获取id
    for (var i = 0; i < pics.length; i++) {
      wx.uploadFile({
        url: getImgUrl,
        filePath: pics[i],
        name: 'file',
        formData: null,
        success: (resp) => {
          that.data.pageData[that.data.current].urlPics.push(JSON.parse(resp.data).data[0])
          degree++;
          if (pics.length == degree) {
            that.uploadInfo(inpText, SendchildrenId, that.data.pageData[that.data.current].urlPics)
          }

        },
        fail: (res) => {
          if (msg == "失败") {
            return false
          }
        },
        complete: (res) => {
          wx.hideLoading();
        }
      });
    }
  },

  // 上传照片获取
  // 上传员工信息
  uploadInfo: function (inpText, SendchildrenId, urlPics){
    var that = this;
    wx.request({
      url: that.data.current == 0 ? addStudentEatRecordUrl : addStudentSleepRecordUrl,
      method: 'POST',
      data: {
        "desc": inpText,
        "organizationId": this.data.organizationId,
        "staffId": this.data.staffId,
        "studentIds": SendchildrenId,
        "urls": urlPics
      },
      success: function (res) {
        wx.hideLoading()
        if (res.data.msg == "成功") {
          wx.hideLoading();
          wx.showToast({
            title: '正在刷新...',
            icon: 'success',
            duration: 2000,
            success: function(){
              that.reloadPage();
            }
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: '出错啦，请稍后再试',
        })
      }
    })
  },

  //没有可以发送的学生的时候弹出
  nosubmit: function() {
    wx.showModal({
      title: '午餐情况已经发送完了',
      content: '你还想干啥子嘛！！！！',
      success(res) {
        if (res.confirm) {
          wx.switchTab({
            url: '../../../../tabBar/mainFunction/mainFunction'
          })
        }
      }
    })
  },
  TabNoonSleep:function(){
    let that = this;
    that.setData({
      current: 1
    })
    wx.setNavigationBarTitle({
      title: '午睡情况填写'
    })
  },
  TabNoonEat:function(){
    let that = this
    that.setData({
      current: 0
    })
    wx.setNavigationBarTitle({
      title: '拍摄午餐情况'
    })

  },
  bindchange:function(e){
    let that = this
    switch (e.detail.current){
      case 0:
        wx.setNavigationBarTitle({
          title: '拍摄午餐情况'
        })
        break;
        case 1:
        wx.setNavigationBarTitle({
          title: '午睡情况填写'
        })
    }

    if (that.data.current == 0) {
      that.setData({
        'pageData[0].TabTitle': !that.data.pageData[0].TabTitle
      })
    }
    else {
      that.setData({
        'pageData[1].TabTitle': !that.data.pageData[1].TabTitle
      })
    }
  },
	// 弹出输入框
	popModel:function(){
		let that = this;
		that.setData({
			ismodel: !that.data.ismodel,
			isscroll:!that.data.isscroll
		})
	},

	// 隐藏输入框
	hiddentModel:function(){
		let that = this
		that.setData({
			ismodel: !that.data.ismodel,
			isscroll:!that.data.isscroll
		})
	},

	// 确认输入
	handleText:function(){
    let that = this
    if (that.data.current == 0) {
      that.setData({
        'pageData[0].inpTextarea': that.data.pageData[0].inpText,
        ismodel: !that.data.ismodel,
        isscroll: !that.data.isscroll
      })
    }
    else {
      that.setData({
        'pageData[1].inpTextarea': that.data.pageData[1].inpText,
        ismodel: !that.data.ismodel,
        isscroll: !that.data.isscroll
      })
    }
	},

  // 刷新页面(重置数据/重新执行onload)
  reloadPage: function () {
    this.setData({
      pageData: [ // index 0 午餐数据 / index 1 午睡数据
        {
          isubmit: true, // 还有学生没有发送
          TabTitle: true,
          currentId: 0, // 未发送和已发送
          files: [],
          checkboxItem: {
            name: 'all',
            value: '全选',
            checked: true
          },
          situationIndex: 1,
          pics: [],     //本地上传图片的数组
          urlPics: [],  //转换为url的数组
          unsendStudentList: [], //午睡情况 未发送学生列表
          sendStudentList: [], //午睡情况 已发送学生列表
          studentId: '',       //发送和未发送那里的学生ID
          SendchildrenId: [],  //选择发送的学生ID
          inpText: '还有需要特别说明的吗？', //要什么要说的咩
          inpTextarea: '还有需要特别说明的吗？'
        },
        {
          isubmit: true,
          TabTitle: true,
          currentId: 0,
          files: [],
          checkboxItem: {
            name: 'all',
            value: '全选',
            checked: true
          },
          situationIndex: 1,
          pics: [],
          urlPics: [],
          unsendStudentList: [],
          sendStudentList: [],
          studentId: '',
          SendchildrenId: [],
          inpText: '还有需要特别说明的吗？',
          inpTextarea: '还有需要特别说明的吗？'
        }
      ]
    })
    this.onLoad();
  }
})